<?php
function _e(){
	echo "<pre>";
	$objs = func_get_args();
	foreach($objs as $obj) {print_r($obj);echo "<br>";}
	echo "</pre>";
	exit;
}
function mk_dir($dir, $mode = 0777) {
	if (is_dir($dir) || @mkdir($dir, $mode))
		return true;
	if (!mk_dir(dirname($dir), $mode))
		return false;
	@mkdir($dir, $mode);
}
function getColByArr($arr,$field){
	$row = array();
	foreach($arr as $k=>$v){
		$row[] = $v[$field];
	}
	return $row;
}
function load_class($path){
	$arr = explode(",",$path);
	foreach($arr as $v){
		require_once $v;
	}
}
function load_cnf($name,$key=''){
	$cnf = include APPPATH.'data/cnf/'.$name.'.php';
	if($key){
		$newcnf = array();
		foreach($cnf as $k=>$v){
			if(stripos($k,$key)!==false) $newcnf[$k] = $v;
		}
		$cnf = $newcnf;
	}
	return $cnf;
}
function load_model($name,$data=array()){
	$new_model_name = 'model_val'.rand(1,100);
	$str = str_replace(array("<?php\r\n","<?php\n","\n?>"),'',file_get_contents(APPPATH.'model/default/'.$name.'.php'));
	$str = 'function '.$new_model_name.'($data){'.$str.'}';
	//echo $str;
	@eval($str);
	$result = $new_model_name($data);
	return $result;
}
function delete_slash(&$data){
	if(get_magic_quotes_gpc()){
		$data=array_map('stripslashes_deep',$data);
	}
}
function stripslashes_deep($value){
	$value=is_array($value)?array_map('stripslashes_deep',$value):stripslashes($value);
	return $value;
}
function only_thread(){
	$cmd = "ps ux | grep '" . implode(" ",$_SERVER['argv']) . "' |grep -v '/bin/sh -c' | grep -v 'grep' -c";
	while(1)
	{
		unset($arrRtn);
		exec($cmd, $arrRtn);
		$prcesscnt = intval($arrRtn[0]);
		if($prcesscnt > 1)
		{
			print $cmd."\n";
			print "There is running another instance of current process, exit @ ".date("Y-m-d H:i:s")."\n";
			//sleep(60*1);
			exit;
		}
		else
			break;
	}
}
function get_table_field($db,$table){
	$path = SYSPATH."data/cache/table/".str_replace(array(',','.'),'_',$db->host.'_'.$db->database.'_'.$table)."_field.php";
	if(!is_file($path)||time()-filemtime($path)>60*10){
		$tableArr = explode(',',$table);
		$field = array();
		foreach($tableArr as $v){
			$sql = "show columns from ".$v;
			$arr = $db->getAll($sql);
			foreach($arr as $v){
				$field[$v['Field']] = $v['Type'];
			}
		}
		file_put_contents($path,"<?php\n return ".var_export($field, true)."\n?>");
	}
	$field = include $path;
	return $field;
}
function timezoneConvert($time, $timeZoneTo = "PRC", $reverse = false){
	if($time == '0000-00-00 00:00:00') return $time;
	if(trim($time) == ""){
		return "";
	}
	if(trim($timeZoneTo) == ""){
		$timeZoneTo = "PRC";
	}
	$timezoneOld = date_default_timezone_get();
	$curTime = strtotime($time);
	date_default_timezone_set($timeZoneTo);
	if($reverse){
		$curTime = strtotime($time);
		date_default_timezone_set($timezoneOld);
	}
	$curDate = date("Y-m-d H:i:s", $curTime);
	date_default_timezone_set($timezoneOld);
	return $curDate; 
}
function dir_writeable($dir) {
    if(!is_dir($dir)) {
        @mkdir($dir, 0777);
    }
    if(is_dir($dir)) {
        if($fp = @fopen("$dir/test.txt", 'w')) {
            @fclose($fp);
            @unlink("$dir/test.txt");
            $writeable = true;
        } else {
            $writeable = false;
        }
    }
    return $writeable;
}
function clean_xss(&$string, $low = False)
{
	if (! is_array ( $string ))
	{
		$string = trim ( $string );
		$string = strip_tags ( $string );
		$string = htmlspecialchars ( $string );
		if ($low)
		{
			return True;
		}
		$string = str_replace ( array ('"', "\\", "'", "/", "..", "../", "./", "//" ), '', $string );
		$no = '/%0[0-8bcef]/';
		$string = preg_replace ( $no, '', $string );
		$no = '/%1[0-9a-f]/';
		$string = preg_replace ( $no, '', $string );
		$no = '/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]+/S';
		$string = preg_replace ( $no, '', $string );
		return True;
	}
	$keys = array_keys ( $string );
	foreach ( $keys as $key )
	{
		clean_xss ( $string [$key] );
	}
}
function get_table_row($db,$table,$id){
	$cnf = load_cnf($table);
	$where = '1 = 1';
	$table_name = $cnf['table'];
	$i = 1;
	while(true){
		$i++;
		if($cnf['table_'.$i]){
			$where .= " AND {$cnf['table_'.$i]}.{$cnf['relate_id']} = {$cnf['table_1']}.{$cnf['relate_id']}";
		}else{
			break;
		}
	}
	$where .= " AND {$cnf['main_table']}.{$cnf['field_id']} = {$id}";
	$sql = "SELECT * FROM {$table_name} WHERE {$where}";
	$result = $db->getRow($sql);
	return $result;
}
function select_db($dbname='default'){
	$dbcnf = include APPDATA.'cnf/database.php';
	$db = new Mysql($dbcnf[$dbname]);
	return $db;
}
$application = null;
function runapp(){
	global $application;
	$application = new main_act();
	if(!empty($_SERVER['argv'][1])){
		for($i=1;$i<count($_SERVER['argv']);$i++){
			$row = explode(":",$_SERVER['argv'][$i]);
			$_GET[$row[0]] = $row[1];
		}
	}
	$act = $_GET["act"];
	if(empty($act)) $act = 'index';
	if($_GET["action"]) $application->action = $_GET["action"];
	if(!$application->action) $application->action = end(explode('/',dirname($_SERVER['REQUEST_URI'])));
	$application->method = $act;
	if(method_exists($application, $act)){
		if(method_exists($application, 'init')){
			$application->init();
		}
		$application->$act();
	}else{
		$application->show_404();
	}
}
function g_autoload($className)
{
	global $router;
    $classDir = array(APPPATH.'lib/',SYSPATH.'core/');
	if($router) $classDir[] = APPPATH.$router->application_dir;
	$user_autoload = @include APPDATA.'cnf/autoload.php';
	if(count($user_autoload)>0) $classDir = array_merge($user_autoload,$classDir);
	foreach($classDir as $v){
		$path = $v.$className.'.php';
		if(is_file($path)){
			require $path;
			break;
		}
	}
}
spl_autoload_register('g_autoload');
?>